<template>
    <div class="main-containers">
        <div class="search">
            <Form inline>
                <FormItem>
                    <Input type="text" clearable v-model="hm_name" placeholder="请输入游资名称">
                    </Input>
                </FormItem>
                <FormItem>
                    <Input type="text" clearable v-model="ts_code" placeholder="请输入股票代码">
                    </Input>
                </FormItem>
                <FormItem>
                    <DatePicker :model-value="trade_date" format="yyyy-MM-dd" type="date" placeholder=""
                        style="width: 200px" @on-change="ChnageDateHandler" />
                </FormItem>
                <FormItem>
                    <Space>
                        <Button type="primary" @click="SearchData">搜索</Button>
                        <Button type="primary" @click="LoadTushareDataHandler" :loading="loading">获取当日数据</Button>
                    </Space>
                </FormItem>
                <FormItem>
                    <Space>
                        <Button type="error" size="small" @click="CoustHname('方新侠')">方新侠</Button>
                    </Space>
                </FormItem>
            </Form>
        </div>
        <Table border stripe :columns="columns" :data="tableData" class="customtable">
            <template #query="{ row }">
                <Space>
                    <Button type="primary" icon="ios-search" @click="IconSearch(row)">查询</Button>
                </Space>
            </template>
            <template #buyAmount="{ row }">
                <Text strong size="large" type="danger">{{ convertAmount(row.buyAmount) }}</Text>
            </template>
            <template #sellAmount="{ row }">
                <Text size="large" type="success" strong>{{ convertAmount(row.sellAmount) }}</Text>
            </template>
            <template #netAmount="{ row }">
                <Text strong size="large" v-if="row.netAmount < 0">{{
                    convertAmount(row.netAmount) }}
                </Text>
                <Text strong size="large" v-if="row.netAmount > 0">{{ convertAmount(row.netAmount) }}
                </Text>
            </template>
        </Table>
        <div class="page-container">
            <Page :total="total" :page-size="size" @on-change="PageChangeHandler" />
        </div>

    </div>
</template>
<script setup>
import { ref, onMounted } from 'vue'
import { loadTushareData, queryTushareData } from '@/api/tushare'
import { Message } from 'view-ui-plus';
import { convertAmount } from '@/utils/tools'


// 获取当前日期并格式化为 yyyyMMdd
const getCurrentDateFormatted = () => {
    const date = new Date()
    const dayOfWeek = date.getDay()
    const hour = date.getHours()

    // 判断是否为交易日（周一到周五）
    const isTradingDay = dayOfWeek >= 1 && dayOfWeek <= 5

    // 如果不是交易日，返回上一个交易日
    if (!isTradingDay) {
        return getPreviousTradingDay(date)
    }

    // 如果是交易日，判断是否在晚上7点之后
    if (hour < 19) {
        return getPreviousTradingDay(date)
    }

    return formatDateToYYYYMMDD(date)
}

// 获取上一个交易日
const getPreviousTradingDay = (date) => {
    const previousDate = new Date(date)
    do {
        previousDate.setDate(previousDate.getDate() - 1)
    } while (previousDate.getDay() === 0 || previousDate.getDay() === 6) // 跳过周末
    return formatDateToYYYYMMDD(previousDate)
}

// 将日期格式化为 yyyyMMdd
const formatDateToYYYYMMDD = (dateStr) => {
    const date = new Date(dateStr)
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    return `${year}${month}${day}`
}
const hm_name = ref('')
const trade_date = ref(getCurrentDateFormatted()) // 初始化为当前日期
const ts_code = ref('')


// 页面初始话
onMounted(async () => {
    QueryTushareDataHandler()
})

// DOTO 搜索数据
const SearchData = () => {
    QueryTushareDataHandler()
}
// 日期选择器改变事件
const ChnageDateHandler = (date) => {
    const formattedDate = formatDateToYYYYMMDD(date)
    trade_date.value = formattedDate
}

// 加载当日游资数据
const loading = ref(false)
const LoadTushareDataHandler = async () => {
    loading.value = true
    const params = {
        tradeDate: trade_date.value,

    }
    const res = await loadTushareData(params)
    loading.value = false
    Message.success(res.message)
}


// 查询游资数据
const page = ref(1)
const size = ref(13)
const total = ref(0)
const tableData = ref([])
const columns = [
    { title: "日期", key: "tradeDate" },
    { title: "股票", key: "tsName" },
    { title: "代码", key: "tsCode" },
    { title: "游资", key: "hmName" },
    { title: "买入金额", slot: "buyAmount" },
    { title: "卖出金额", slot: "sellAmount" },
    { title: "净买入金额", slot: "netAmount" },
    { title: "游资机构", key: "hmOrgs", width: 400 },
    { title: "查询", slot: "query", align: "center" },
]
const QueryTushareDataHandler = async () => {
    const params = {
        tradeDate: trade_date.value,
        hmName: hm_name.value,
        tsCode: ts_code.value,
        page: page.value,
        size: size.value
    }
    const res = await queryTushareData(params)
    tableData.value = res.data.list
    total.value = res.data.total
}

// 分页改变
const PageChangeHandler = (pageNum) => {
    page.value = pageNum
    QueryTushareDataHandler()
}


// 常用游资彩讯
const CoustHname = (name) => {
    hm_name.value = name
    QueryTushareDataHandler()
}
// 股票查询
const IconSearch = (row) => {
    ts_code.value = row.tsCode
    hm_name.value = ''
    QueryTushareDataHandler()
}
</script>
<style lang="scss" scoped>
// 使用 :deep() 进行样式穿透
:deep(.ivu-form-item) {
    margin-bottom: 0 !important;
}
</style>